package com.caimiao.miao.library.usb.accessory;

import java.util.LinkedList;

/**
 * USB数据缓存：读写数据
 */
public class UsbDataBuffer {
    private static final String TAG = "UsbDataBuffer";
    private LinkedList<Command> mWriteQueue;
    private String mReadBuffer;

    protected UsbDataBuffer() {
        mWriteQueue = new LinkedList<>();
        mReadBuffer = "";
    }

    /***********************************写缓存************************************************/

    public void addCommandToWriteQueue(Command command) {
        synchronized (mWriteQueue) {
            int location = 0;
            boolean exit = false;
            for (Command comm : mWriteQueue) {
                if (command.getCode() == comm.getCode()) {
                    location = mWriteQueue.indexOf(comm);
                    exit = true;
                    break;
                }
            }

            if (exit)
                mWriteQueue.set(location, command);
            else
                mWriteQueue.addFirst(command);
        }
    }

    public void addLastCmdToWriteQueue(Command command) {
        synchronized (mWriteQueue) {
            int location = 0;
            boolean exit = false;
            for (Command comm : mWriteQueue) {
                if (command.getCode() == comm.getCode()) {
                    location = mWriteQueue.indexOf(comm);
                    exit = true;
                }
            }

            if (exit)
                mWriteQueue.set(location, command);
            else
                mWriteQueue.add(command);
        }
    }

    /**
     * 获取队列第一个元素
     */
    public Command nextCommand() {
        if (mWriteQueue.isEmpty()) return null;
        synchronized (mWriteQueue) {
            return mWriteQueue.removeFirst();
        }
    }

    public void clearWriteQueue() {
        synchronized (mWriteQueue) {
            mWriteQueue.clear();
        }
    }

    /*********************************读缓存**************************************************/

    public void setReadData(int count, byte[] usbData) {
        synchronized (mReadBuffer) {
            for (int i = 0; i < count; i++) {
                mReadBuffer += (char) ((usbData[i]) & 0xFF);
            }
        }
    }

    public char[] getReadData() {
        String report = mReadBuffer;
        return report.toCharArray();
    }

    public void clearReadData() {
        synchronized (mReadBuffer) {
            mReadBuffer = "";
        }
    }
}
